﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Collections;
using SubSonic;

public partial class Controls_SelectContract : System.Web.UI.UserControl
{
    public event SelectContract Click;
    private Guid _Contractid;
    public Guid Contractid
    {
        get { return _Contractid; }
        set
        {
            _Contractid = value;
        }
    }

    private string _Date;
    public string Date
    {
        get { return _Date; }
        set
        {
            _Date = value;
        }
    }

    private string _Role;
    public string Role
    {
        get { return _Role; }
        set
        {
            _Role = value;
        }
    }

    private string _VillageName;
    public string VillageName
    {
        get { return _VillageName; }
        set
        {
          _VillageName = value;
        }
    }
    private string _ContractNumber;
    public string ContractNumber
    {
        get { return _ContractNumber; }
        set
        {
            _ContractNumber = value;
        }
    }
    private string _UserId;
    public string UserId
    {
        get { return _UserId; }
        set
        {
            _UserId = value;
        }
    }
    private string _Family;
    public string Family
    {
        get { return _Family; }
        set
        {
            _Family = value;
        }
    }
   
    protected void Page_Load(object sender, EventArgs e)
    {
        Lblstatus.Text = "";
        //if (!Page.IsPostBack)
        //{
        //    AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
        //    trigger.ControlID = DropDownVillage.UniqueID;
        //    UpdatePanel1.Triggers.Add(trigger);
        //}
        //Page.DataBind();


    }
    protected void RadioButtonListSelector_SelectedIndexChanged(object sender, EventArgs e)
    {
        //RadioButtonList r=(RadioButtonList) LoginView2.FindControl("RadioButtonListSelector");
        //MultiView m = (MultiView)LoginView2.FindControl("MultiView1");
        //if (r.SelectedItem.Value == "Village")
        //{
        //    m.ActiveViewIndex = 0;
        //}
        //else
        //{
        //    m.ActiveViewIndex = 1;
        //}
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        try
        {
            BindingGrid();
        }
        catch
        { }
    }

    private void BindingGrid()
    {
        string orderExpression = DataAccess.TblUserDetail.Columns.Name;
        SubSonic.Query tempQuery = new Query(DataAccess.TblUserDetail.Schema);
        tempQuery.OrderBy = SubSonic.OrderBy.Asc("Name");
        if (ViewState["SortExpression"] != null && !ViewState["SortExpression"].ToString().Trim().Equals(String.Empty))
        {
            switch (ViewState["SortExpression"].ToString())
            {
                case "Name":
                    orderExpression = DataAccess.TblUserDetail.Columns.Name;
                    break;
                case "Family":
                    orderExpression = DataAccess.TblUserDetail.Columns.Family;
                    break;
                case "UserName":
                    orderExpression = DataAccess.TblUserDetail.Columns.UserName;
                    break;
            }

            tempQuery.OrderBy = ViewState["SortDirection"] != "Ascending" ? SubSonic.OrderBy.Desc(orderExpression) : SubSonic.OrderBy.Asc(orderExpression);
        }

        if (RadioButtonListRole.SelectedItem.Value == "Advisor")
        {
            if (RadioButtonListAdvisors.SelectedValue == "")
            {
                SubSonic.Query q1 = DataAccess.TblUserDetail.CreateQuery();
                q1.QueryType = SubSonic.QueryType.Select;
                q1.OrderBy = tempQuery.OrderBy;
                q1.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q1.AND(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Advisorhoghooghi");
                q1.OR(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Advisorhaghighi");

                DataSet dt1 = q1.ExecuteDataSet();
                if (dt1.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt1;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " <script>alert('.فرد مورد نظر یافت نشد ')</script>";
                    cleargrid();
                }
            }
        }

        if (RadioButtonListRole.SelectedItem.Value == "Advisor")
        {
            if (RadioButtonListAdvisors.SelectedValue != "")
            {
                if (RadioButtonListAdvisors.SelectedItem.Value == "Advisorhoghooghi")
                {
                    SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                    q.QueryType = SubSonic.QueryType.Select;
                    q.OrderBy = tempQuery.OrderBy;
                    q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                    q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Advisorhoghooghi");
                    DataSet dt = q.ExecuteDataSet();
                    if (dt.Tables[0].Rows.Count > 0)
                    {
                        GridViewUsers.DataSource = dt;
                        GridViewUsers.DataBind();
                    }
                    else
                    {
                        Lblstatus.Text = " <script>alert('.فرد مورد نظر یافت نشد ')</script>";
                        cleargrid();
                    }
                }
                if (RadioButtonListAdvisors.SelectedItem.Value == "Advisorhaghighi")
                {
                    SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                    q.QueryType = SubSonic.QueryType.Select;
                    q.OrderBy = tempQuery.OrderBy;
                    q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                    q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Advisorhaghighi");
                    DataSet dt = q.ExecuteDataSet();
                    if (dt.Tables[0].Rows.Count > 0)
                    {
                        GridViewUsers.DataSource = dt;
                        GridViewUsers.DataBind();
                    }
                    else
                    {
                        Lblstatus.Text = " <script>alert('.فرد مورد نظر یافت نشد ')</script>";
                        cleargrid();
                    }
                }
            }
        }
        if (RadioButtonListRole.SelectedItem.Value == "Surveyor")
        {
            if (RadioButtonListSurveyor.SelectedItem.Value == "Advisorhoghooghi")
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.OrderBy = tempQuery.OrderBy;
                q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Surveyorhoghooghi");
                DataSet dt = q.ExecuteDataSet();
                if (dt.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " <script>alert('.فرد مورد نظر یافت نشد ')</script>";
                    cleargrid();
                }
            }
            if (RadioButtonListSurveyor.SelectedItem.Value == "Advisorhaghighi")
            {
                SubSonic.Query q = DataAccess.TblUserDetail.CreateQuery();
                q.QueryType = SubSonic.QueryType.Select;
                q.OrderBy = tempQuery.OrderBy;
                q.AddWhere(DataAccess.TblUserDetail.Columns.Family, SubSonic.Comparison.Like, "%" + TxtFamily.Text + "%");
                q.AddWhere(DataAccess.TblUserDetail.Columns.Role, SubSonic.Comparison.Equals, "Surveyorhaghighi");
                DataSet dt = q.ExecuteDataSet();
                if (dt.Tables[0].Rows.Count > 0)
                {
                    GridViewUsers.DataSource = dt;
                    GridViewUsers.DataBind();
                }
                else
                {
                    Lblstatus.Text = " <script>alert('.فرد مورد نظر یافت نشد ')</script>";
                    cleargrid();
                }
            }
        }
    }

    protected void RadioButtonListRole_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (RadioButtonListRole.SelectedItem.Value == "Advisor")
        {
            RadioButtonListSurveyor.Visible = false;
            RadioButtonListAdvisors.Visible = true;
            Role = "Advisor";
        }
        else
        {
            RadioButtonListAdvisors.Visible = false;
            RadioButtonListSurveyor.Visible = true;
            Role = "Surveyor";
        }
        
    }
   

    public void cleargrid()
    {
        GridViewUsers.DataSource = null;
        GridViewUsers.DataBind();
    }
    protected void GridViewUsers_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    protected void GridViewContracts_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Business.Calender cal = new Business.Calender();
                string pdate = cal.MiladiToPersian(Convert.ToDateTime(e.Row.Cells[1].Text));
                e.Row.Cells[1].Text = pdate;
                IDataReader t = DataAccess.TblUserDetail.FetchByParameter(DataAccess.TblUserDetail.Columns.UserId, e.Row.Cells[9].Text);
                if (t.Read())
                {
                    e.Row.Cells[2].Text = t["Name"].ToString() + " / " + t["Family"].ToString();
                    t.Close();
                }

                if (e.Row.Cells[3].Text == bool.TrueString)
                    e.Row.Cells[3].Text = "قرارداد مشاوره";
                if (e.Row.Cells[3].Text == bool.FalseString)
                    e.Row.Cells[3].Text = "قرارداد نقشه برداری";
                DataAccess.TblVillage vil = DataAccess.TblVillage.FetchByID(e.Row.Cells[11].Text);
                e.Row.Cells[5].Text = vil.Name;
                DataAccess.TblDehestan deh = DataAccess.TblDehestan.FetchByID(vil.DehstanId);
                e.Row.Cells[6].Text = deh.Name;
                DataAccess.TblBakhsh bakhsh = DataAccess.TblBakhsh.FetchByID(deh.BakhshId);
                e.Row.Cells[7].Text = bakhsh.Name;
                DataAccess.TblCity city = DataAccess.TblCity.FetchByID(bakhsh.CityId);
                e.Row.Cells[8].Text = city.Name;
                e.Row.Cells[9].Visible = false;
                e.Row.Cells[11].Visible = false;
            }
        }
        catch
        {
        }
    }

   
    protected void RadioButtonListAdvisors_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void GridViewContracts_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName != "Sort")
        {
            int id = Convert.ToInt32(e.CommandArgument);
            switch (e.CommandName)
            {
                case "Select":
                    Guid idc = new Guid(GridViewContracts.DataKeys[id].Value.ToString());
                    Contractid = idc;
                    Date = GridViewContracts.Rows[id].Cells[1].Text;
                    VillageName = GridViewContracts.Rows[id].Cells[5].Text;
                    ContractNumber = GridViewContracts.Rows[id].Cells[0].Text;
                    if (Session["UserIdUpload"] != null)
                    {
                        MembershipUser u = Membership.GetUser(Session["UserIdUpload"]);
                        if (Roles.IsUserInRole(u.UserName, "Advisor"))
                        {

                            Role = "Advisor";
                        }
                        if (Roles.IsUserInRole(u.UserName, "Surveyor"))
                        {

                            Role = "Surveyor";
                        }
                    }
                    //LinkButton linkButton = e.CommandSource as LinkButton;
                    //GridViewRow gridViewRow = linkButton.Parent.Parent as GridViewRow;

                    //gridViewRow.BackColor = System.Drawing.Color.RoyalBlue;
                    Click(this);
                    //return Contractid;
                    break;
            }
        }
    }
   
   

   

    protected void ButtonCancelAdmin_Click(object sender, EventArgs e)
    {
        clearadmin();
        MultiViewAdmin.ActiveViewIndex = 0;
    }
    public void clearadmin()
    {
        TxtFamily.Text = "";
      
        GridViewContracts.DataSource = null;
        GridViewContracts.DataBind();
        GridViewUsers.DataSource = null;
        GridViewUsers.DataBind();
       
        MultiViewAdmin.ActiveViewIndex = 0;
    }
    protected void Button6_Click(object sender, EventArgs e)
    {
        clearadmin();
        MultiViewAdmin.ActiveViewIndex = -1;
    }

    protected void GridViewUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName != "Sort")
        {
            int id = Convert.ToInt32(e.CommandArgument);
            switch (e.CommandName)
            {
                case "Select":
                    Guid userid = new Guid(GridViewUsers.DataKeys[id].Value.ToString());
                    UserId = userid.ToString();
                    Family = GridViewUsers.Rows[id].Cells[0].Text + " " + GridViewUsers.Rows[id].Cells[1].Text;

                    Session["UserIdUpload"] = userid;
                    GridViewContracts.DataSource =
                        DataAccess.TblContract.FetchByParameter(DataAccess.TblContract.Columns.UserId,
                                                                SubSonic.Comparison.Equals, userid,
                                                                SubSonic.OrderBy.Asc("ContractNumber"));
                    GridViewContracts.DataBind();
                    MultiViewAdmin.ActiveViewIndex = 2;
                    break;
            }
        }
    }

    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (RadioButtonList1.SelectedItem.Value == "Family")
        {
            MultiViewAdmin.ActiveViewIndex = 1;
        } 
        if (RadioButtonList1.SelectedItem.Value == "Village")
        {
            MultiViewAdmin.ActiveViewIndex = 0;
        }
    }
  protected void  DropDownVillage_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        GridViewContracts.DataSource = DataAccess.TblContract.FetchByParameter(DataAccess.TblContract.Columns.VillageId, SubSonic.Comparison.Equals, DropDownVillage.SelectedValue, SubSonic.OrderBy.Asc("ContractNumber"));
        GridViewContracts.DataBind();
        MultiViewAdmin.ActiveViewIndex = 2;
    }
    catch
    { }
    //Page.DataBind();
}
  protected void DropDownVillage_TextChanged(object sender, EventArgs e)
  {

  }
  protected void GridViewContracts_SelectedIndexChanged(object sender, EventArgs e)
  {

  }
  private void SortDDL(ref DropDownList objDDL)
  {
      ArrayList textList = new ArrayList();
      ArrayList valueList = new ArrayList();


      foreach (ListItem li in objDDL.Items)
      {
          textList.Add(li.Text);
      }

      textList.Sort();


      foreach (object item in textList)
      {
          string value = objDDL.Items.FindByText(item.ToString()).Value;
          valueList.Add(value);
      }
      objDDL.Items.Clear();

      for (int i = 0; i < textList.Count; i++)
      {
          ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
          objDDL.Items.Add(objItem);
      }
  }
  protected void GridViewUsers_OnSort(object sender, GridViewSortEventArgs e)
  {
      // get values from viewstate
      String sortExpression = ViewState["SortExpression"] as string;
      String sortDirection = ViewState["SortDirection"] as string;

      // on first time header clicked ( including different header), sort ASCENDING
      if (e.SortExpression != sortExpression)
      {
          sortExpression = e.SortExpression;
          sortDirection = "Ascending";
      }
      // on second time header clicked, toggle sort
      else
      {
          if (sortDirection == "Ascending")
          {
              sortExpression = e.SortExpression;
              sortDirection = "Descending";
          }
          // Descending
          else
          {
              sortExpression = e.SortExpression;
              sortDirection = "Ascending";
          }
      }

      // save state for next time

      ViewState["SortExpression"] = sortExpression;
      ViewState["SortDirection"] = sortDirection;
      BindingGrid();
  }


    protected void GridViewUsers_PreRender(object sender, EventArgs e)
    {
        GridViewPreRender(GridViewUsers);
    }

    protected void GridViewContract_PreRender(object sender, EventArgs e)
    {
        GridViewPreRender(GridViewContracts);
    }

    private void GridViewPreRender(GridView gridView)
    {
        if (gridView.Rows.Count > 0)
        {
            //This replaces <td> with <th> and adds the scope attribute
            gridView.UseAccessibleHeader = true;

            //This will add the <thead> and <tbody> elements
            gridView.HeaderRow.TableSection = TableRowSection.TableHeader;

            //This adds the <tfoot> element. 
            //Remove if you don't have a footer row
            gridView.FooterRow.TableSection = TableRowSection.TableFooter;
        }
    }
}
public delegate void SelectContract(object sender);